package com.kotlin.lib

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**?
 * 通过provideDelegate可以选择动态选择是否代理该字段。Todo：使用场景需要网上查阅更多资料
 */
class RealDelegateImp : ReadWriteProperty<ProvideDelegatePerson, String?> {
    private val map = mutableMapOf<String, String?>()
    override fun setValue(thisRef: ProvideDelegatePerson, property: KProperty<*>, value: String?) {
        println("${property.name} set to $value")
        map[property.name] = value
        /*when (property.name) {
            "name" -> thisRef.name = value
            "address" -> thisRef.address = value
        }*/
    }

    override fun getValue(thisRef: ProvideDelegatePerson, property: KProperty<*>): String? {
        println("get ${property.name} ")
        return (map[property.name])
    }

}

class ProvideDelegateLauncher {
    operator fun provideDelegate(
        thisRef: ProvideDelegatePerson,
        property: KProperty<*>
    ): ReadWriteProperty<ProvideDelegatePerson, String?> {
        return when (property.name) {
            "name", "address" -> RealDelegateImp()
            else -> throw UnsupportedOperationException("filed is not support")
        }
    }
}

class ProvideDelegatePerson {
    var name: String? by ProvideDelegateLauncher()
    var address: String? by ProvideDelegateLauncher()

}


fun main() {
    val person = ProvideDelegatePerson()
    println("${person.name} ${person.address}")
    person.name = "zhangsan"
    person.address = "beiJin"

    println("${person.name} ${person.address}")

}